import pygame
from bullet import *
import random


class Plane(object):
    def __init__(self, screen, name):

        # 飞机的名称
        self.name = name

        # 设置要显示内容的窗口
        self.screen = screen
        self.image = pygame.image.load(self.image_name).convert()

        # 用来存储英雄飞机发射的所有子弹
        self.bullet_list = []

    def display(self):
        # 更新飞机的位置
        self.screen.blit(self.image, (self.x, self.y))

        # 用来存放需要删除的对象信息
        need_del_list = []

        # 保存需要删除的对象
        for item in self.bullet_list:
            if item.judge():
                need_del_list.append(item)

        # 删除bullet_list中需要删除的对象
        for del_item in need_del_list:
            self.bullet_list.remove(del_item)

        for bullet in self.bullet_list:
            bullet.display()
            bullet.move()

    def launch_bullet(self):
        new_bullet = PublicBullet(self.x, self.y, self.screen, self.name)
        self.bullet_list.append(new_bullet)


class HeroPlane(Plane):

    def __init__(self, screen, name):
        # 设置飞机默认的位置
        self.x = 240
        self.y = 600

        self.image_name = "./feiji/hero.gif"

        super().__init__(screen, name)
        self.rect = self.image.get_rect()  # 创建飞机的矩形区域
        self.destroy = False  # 初始化destroy属性为False

    def move_left(self):
        if self.x > 0:  # 判断是否到达左边界
            self.x -= 5

    def move_right(self):
        if self.x < 480 - self.image.get_width():  # 判断是否到达右边界
            self.x += 5

    def move_up(self):
        if self.y > 0:  # 判断是否到达上边界
            self.y -= 5

    def move_down(self):
        if self.y < 800 - self.image.get_height():  # 判断是否到达下边界
            self.y += 5


class EnemyPlane(Plane):
    # 重写父类的__init_方法
    def __init__(self, screen, name):

        # 设置飞机默认的位置
        self.x = 240
        self.y = 100
        self.image_name = "./feiji/enemy-1.gif"

        # 调用父类的__init__方法
        super().__init__(screen, name)
        self.rect = self.image.get_rect()  # 创建飞机的矩形区域
        self.destroy = False  # 初始化destroy属性为False
        # 移动方向
        self.direction = "right"

    def move(self):
        # 如果碰到了右边的边界，那么就往左走，如果碰到了左边的边界，那么就往右走
        if self.direction == "right":
            self.x += 2
        elif self.direction == "left":
            self.x -= 2
        if self.x > 480 - 50:
            self.direction = "left"
        elif self.x < 0:
            self.direction = "right"

    def launch_bullet(self):
        number = random.randint(1, 100)
        if number == 88:
            super().launch_bullet()

    def move(self):
        if self.direction == "right":
            if self.x < 480 - self.image.get_width():  # 判断是否到达右边界
                self.x += 2
            else:
                self.direction = "left"
        elif self.direction == "left":
            if self.x > 0:  # 判断是否到达左边界
                self.x -= 2
            else:
                self.direction = "right"
